/*
* CourseController.java
* Created on  2014-4-19 下午4:53
* 版本       修改时间          作者      修改内容
* V1.0.1    2014-4-19       gaoxinyu    初始版本
*
*/
package com.genghis.ptas.course;

import com.genghis.core.autocomplete.service.AutoCompleteService;
import com.genghis.core.page.entity.Page;
import com.genghis.core.page.entity.PageParameter;
import com.genghis.ptas.classify.entity.Type;
import com.genghis.ptas.classify.entity.TypeValues;
import com.genghis.ptas.classify.service.ClassifyService;
import com.genghis.ptas.classroom.entity.ClassroomStudent;
import com.genghis.ptas.classroom.service.ClassroomService;
import com.genghis.ptas.constant.DictConstant;
import com.genghis.ptas.course.entity.CourseComment;
import com.genghis.ptas.course.entity.CourseInfo;
import com.genghis.ptas.course.service.CourseRegisterService;
import com.genghis.ptas.course.service.CourseService;
import com.genghis.ptas.course.service.CourseStatisticsService;
import com.genghis.ptas.note.entity.Note;
import com.genghis.ptas.note.service.NoteService;
import com.genghis.ptas.note.service.PublicityNoteService;
import com.genghis.ptas.security.entity.User;
import com.genghis.ptas.security.service.UserService;
import com.genghis.ptas.statistic.entity.CourseStatistics;
import com.genghis.ptas.study.entity.StudyRecord;
import com.genghis.ptas.study.service.StudyRecordService;
import com.genghis.ptas.util.FileUp;
import com.genghis.ptas.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;

/**
 * 类的描述信息
 *
 * @author fenxuanzhen
 * @version 1.0.1
 */
@Controller
@Transactional
@RequestMapping("/course/")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private CourseRegisterService courseRegisterService;

    @Autowired
    private StudyRecordService studyRecordService;

    @Autowired
    private AutoCompleteService autoCompleteService;

    @Autowired
    private ClassifyService classifyService;

    @Autowired
    private ClassroomService classroomService;

    @Autowired
    private CourseStatisticsService courseStatisticsService;

    @Autowired
    private NoteService noteService;

    @Autowired
    private PublicityNoteService publicityNoteService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "listAllCourseDo", method = {RequestMethod.GET, RequestMethod.POST})
    public String listAllCourseDo() {
        return "backstage/course/baseinfo/listAllCourseBaseInfoDo";
    }

    @RequestMapping(value = "listAllCourse", method = RequestMethod.POST)
    @ResponseBody
    public Page listAllCourse(PageParameter pageParameter, CourseInfo courseInfo) {
        return courseService.findCoursePageList(pageParameter, courseInfo);
    }

    @RequestMapping(value = "adminWatchCourse", method = {RequestMethod.GET, RequestMethod.POST})
    public String adminWatchCourse(HttpServletRequest request, @RequestParam("id") Integer id) throws ServletException,
            IOException, ParserConfigurationException, SAXException, XPathExpressionException {
        request.setAttribute("scormNodes", courseService.findChapterByCourseId(id));
        request.setAttribute("course", courseService.findCourseByCourseId(id));
        return "backstage/course/watchcourse/watchCourse";
    }

    @RequestMapping(value = "courseInfoDo", method = {RequestMethod.GET, RequestMethod.POST})
    public String courseInfoDo(HttpServletRequest request, @RequestParam("id") Integer id) throws ServletException, IOException {
        request.setAttribute("courseComment", courseService.findCourseCommentByCourseId(id));
        request.setAttribute("course", courseService.findCourseByCourseId(id));
        User user = new User(44);
        String loginName = LoginUserUtil.findLoginUserName();
        if (loginName != null) {
            user = userService.findUserByLoginName(loginName);
        }
        Boolean register = courseRegisterService.checkWhetherRegisterByCourseId(id);
        request.setAttribute("register", register);
        request.setAttribute("userId", user.getId());
        request.setAttribute("isLogin", null != loginName);
        return "frontstage/course/courseInfo";
    }

    @RequestMapping(value = "classroomEnterCourseInfoDo", method = {RequestMethod.GET, RequestMethod.POST})
    public String courseInfoDo(HttpServletRequest request, @RequestParam("classroomInfoId") Integer classroomInfoId, @RequestParam("classroomCourseId") Integer classroomCourseId, @RequestParam("courseId") Integer courseId) throws ServletException, IOException {
        classroomService.changeStudentCourseId(new ClassroomStudent(0, classroomCourseId, classroomInfoId));
        request.setAttribute("courseComment", courseService.findCourseCommentByCourseId(courseId));
        request.setAttribute("course", courseService.findCourseByCourseId(courseId));
        String loginName = LoginUserUtil.findLoginUserName();
        User user = userService.findUserByLoginName(loginName);
        Boolean register = courseRegisterService.checkWhetherRegisterByCourseId(courseId);
        request.setAttribute("register", register);
        request.setAttribute("userId", user.getId());
        request.setAttribute("isLogin", null != loginName);
        return "frontstage/course/courseInfo";
    }

    @RequestMapping(value = "userWatchCourse", method = {RequestMethod.GET})
    public String userWatchCourse(HttpServletRequest request, @RequestParam("id") Integer id) throws ServletException,
            IOException, ParserConfigurationException, SAXException, XPathExpressionException {
        CourseStatistics courseStatistics = courseStatisticsService.findCourseStatisticsByCourseId(id);
        courseStatistics.setTotalNumber(courseStatistics.getTotalNumber() + 1);
        courseStatisticsService.editCourseStatistics(courseStatistics);
        Note note = noteService.findNoteByCourseIdAndUserId(id);
        request.setAttribute("note", note);
        request.setAttribute("noteRelated", noteService.findNoteByType(note).size() == 0 ? new Note() : noteService.findNoteByType(note).get(0));
        request.setAttribute("scormNodes", courseRegisterService.findCourseChapterRegisterByCourseIdAndUserId(id));
        CourseInfo courseInfo = courseService.findCourseByCourseId(id);
        request.setAttribute("course", courseInfo);
        String loginName = LoginUserUtil.findLoginUserName();
        User user = userService.findUserByLoginName(loginName);
        request.setAttribute("userId", user.getId());
        //新增学习记录
        addStudyRecord(courseInfo, user.getId());
        return "frontstage/course/watchCourse";
    }

    private void addStudyRecord(CourseInfo courseInfo, int userId) {
        StudyRecord studyRecord = new StudyRecord();
        studyRecord.setCategory(3);
        studyRecord.setCourseId(courseInfo.getId());
        studyRecord.setUserId(userId);
        studyRecord.setStudyRecord("你学习了课件" + courseInfo.getCourseName());
        studyRecordService.addStudyRecord(studyRecord);
    }


    @RequestMapping(value = "addCourse", method = {RequestMethod.GET, RequestMethod.POST})
    public String addCourse(HttpServletRequest request) {
        List<Type> typeList = classifyService.findAllTypeList();
        List<TypeValues> typeValuesList = classifyService.findAllTypeValueList();
        request.setAttribute("typeList", typeList);
        request.setAttribute("typeValuesList", typeValuesList);
        return "backstage/course/baseinfo/addCourse";
    }

    @RequestMapping(value = "addCourseByUser", method = {RequestMethod.GET, RequestMethod.POST})
    public String addCourseByUser(HttpServletRequest request) {
        List<Type> typeList = classifyService.findAllTypeList();
        List<TypeValues> typeValuesList = classifyService.findAllTypeValueList();
        request.setAttribute("typeList", typeList);
        request.setAttribute("typeValuesList", typeValuesList);
        return "frontstage/course/addCourseByUser";
    }

    @RequestMapping(value = "editCourseInfoDo", method = {RequestMethod.GET, RequestMethod.POST})
    public String editCourseInfoDo(HttpServletRequest request, CourseInfo courseInfo) throws GeneralSecurityException {
        CourseInfo course = courseService.findCourseByCourseId(courseInfo.getId());
        List<Type> typeList = classifyService.findAllTypeList();
        List<TypeValues> typeValuesList = classifyService.findAllTypeValueList();
        request.setAttribute("course", course);
        request.setAttribute("typeList", typeList);
        request.setAttribute("typeValuesList", typeValuesList);
        return "backstage/course/baseinfo/editCourse";
    }

    @RequestMapping(value = "editCourseInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public String editCourseInfo(HttpServletRequest request, @RequestParam("id") Integer id) throws ServletException, IOException, GeneralSecurityException {
        CourseInfo courseInfo = courseService.findCourseByCourseId(id);
        courseInfo.setCourseName(request.getParameter("courseName"));
        courseInfo.setCourseType(Integer.parseInt(request.getParameter("totalNum")));
        String url = request.getParameter("Img");
        if (!courseInfo.getPhotoUrl().equals(url)) {
            String imgUrl = new FileUp().url(request, courseInfo.getPhotoUrl().substring(courseInfo.getPhotoUrl().indexOf("/") + 1, courseInfo.getPhotoUrl().lastIndexOf("/")), "fileImg");
            courseInfo.setPhotoUrl(imgUrl);
        }
        courseService.editCourse(courseInfo);
        autoCompleteService.initAutoComplete();
        request.setAttribute("type", "编辑");
        request.setAttribute("judge", true);
        return "backstage/course/baseinfo/success";
    }

    @RequestMapping(value = "upload", method = {RequestMethod.GET, RequestMethod.POST})
    public String upload(HttpServletRequest request) throws ServletException, IOException, ParserConfigurationException, SAXException, XPathExpressionException {
        CourseInfo courseInfo = new CourseInfo();
        courseInfo.setCourseName(request.getParameter("courseName"));
        courseInfo.setCourseType(Integer.parseInt(request.getParameter("totalNum")));
        request.setAttribute("type", "新增");
        request.setAttribute("uploadResult", true);
        request.setAttribute("judge", courseService.upload(request, courseInfo, "upFile", "fileImg"));
        return "backstage/course/baseinfo/success";
    }

    @RequestMapping(value = "uploadByUser", method = {RequestMethod.GET, RequestMethod.POST})
    public String uploadByUser(HttpServletRequest request) throws ServletException, IOException, ParserConfigurationException, SAXException, XPathExpressionException {
        CourseInfo courseInfo = new CourseInfo();
        courseInfo.setCourseName(request.getParameter("courseName"));
        courseInfo.setCourseType(Integer.parseInt(request.getParameter("courseType")));
        request.setAttribute("type", "新增");
        request.setAttribute("uploadResult", true);
        request.setAttribute("judge", courseService.upload(request, courseInfo, "upFile", "fileImg"));
        return "frontstage/course/addCourseByUser";
    }

    @RequestMapping(value = "checkAuditInfoSubmitState", method = {RequestMethod.GET})
    @ResponseBody
    public Boolean checkAuditInfoSubmitState(@RequestParam("ids") String ids) {
        return courseService.checkAuditInfoAuditState(ids, DictConstant.AUDITING);
    }

    @RequestMapping(value = "changeAuditStateToAudited", method = {RequestMethod.GET})
    @ResponseBody
    public void changeAuditStateToAudited(@RequestParam("ids") String ids) {
        courseService.changeAuditState(ids, DictConstant.AUDIT);
    }


    @RequestMapping(value = "deleteCourseInfo", method = {RequestMethod.DELETE})
    @ResponseBody
    public void delDictDefine(@RequestParam("id") Integer id) throws GeneralSecurityException {
        courseService.deleteCourseInfoById(id);
        autoCompleteService.initAutoComplete();
    }

    @RequestMapping(value = "courseComment", method = {RequestMethod.POST})
    @ResponseBody
    public void courseComment(CourseComment courseComment) throws GeneralSecurityException {
        courseService.addCourseComment(courseComment);
    }

}
